package util;

import com.supermap.data.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

import static socketEnv.Client.message;

/**
 * Created by caolp on 2016/10/30.
 */
public class ListenCounts {
	public String pid = null;
	public DatasetVector datasetVector = null;
	public String cpu;
	public String memory;
	public String time;
	Workspace workspace;
	DatasourceConnectionInfo datasourceConnectionInfo;

	public void ListenCounts() {

	}

	public void getPID() throws Exception {
		RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
		pid = runtimeMXBean.getName().split("@")[0];
		Info.out("当前Java进程的PID为:" + pid);
		datasetVector = getMySqlDataset();
		Info.out("获取到的数据集为" + datasetVector.getName());
	}

	// 根据PID获取当前进程的memory
	public String getMemByPID() throws Exception {
		if (pid == null) {
			return null;
		}
		InputStream is = null;
		InputStreamReader ir = null;
		BufferedReader br = null;
		String line = null;
		String[] array = null;
		try {
			Process p = Runtime.getRuntime().exec(" TASKLIST /NH /FO CSV /FI \"PID EQ " + pid + "\"");
			is = p.getInputStream();
			ir = new InputStreamReader(is);
			br = new BufferedReader(ir);
			while ((line = br.readLine()) != null) {
				if (!"".equals(line)) {
					array = line.split("\",\"");
					line = array[4].replaceAll("\"", "");
					Info.out("当前java进程的内存为：" + line);
					return line;

				}
			}
		} catch (IOException localIOException) {
			throw new Exception("获取进程内存信息出错！");
		} finally {
			if (br != null) {
				br.close();
			}
			if (ir != null) {
				ir.close();
			}
			if (is != null) {
				is.close();
			}
		}
		if (br != null) {
			br.close();
		}
		if (ir != null) {
			ir.close();
		}
		if (is != null) {
			is.close();
		}
		return null;
	}

	// 根据PID获取当前进程的CPU
	public String getCPUByPID() throws Exception {
		if (pid == null) {
			return null;
		}
		InputStream is = null;
		InputStreamReader ir = null;
		BufferedReader br = null;
		String line = null;
		String[] array = null;
		try {
			Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV /FI \"PID EQ " + pid + "\"");
			is = p.getInputStream();
			ir = new InputStreamReader(is);
			br = new BufferedReader(ir);
			while ((line = br.readLine()) != null) {
				if (!"".equals(line)) {
					array = line.split("\",\"");
					line = array[3].replaceAll("\"", "");
					Info.out("当前java进程的CPU为：" + line);
					return line;
				}
			}
		} catch (Exception localException) {
			throw new Exception("获取进程CPU信息出错！");
		} finally {
			if (br != null) {
				br.close();
			}
			if (ir != null) {
				ir.close();
			}
			if (is != null) {
				is.close();
			}
		}
		if (br != null) {
			br.close();
		}
		if (ir != null) {
			ir.close();
		}
		if (is != null) {
			is.close();
		}
		return null;
	}

	public DatasetVector getMySqlDataset() throws Exception {
		// 定义工作空间
		Dataset dataset = null;
		workspace = new Workspace();
		datasourceConnectionInfo = new DatasourceConnectionInfo();
		datasourceConnectionInfo.setEngineType(EngineType.MYSQL);
		datasourceConnectionInfo.setServer("192.168.15.249");
		datasourceConnectionInfo.setDatabase("process");
		datasourceConnectionInfo.setUser("root");
		datasourceConnectionInfo.setPassword("123456");
		datasourceConnectionInfo.setAlias("MYSQL");
		// 打开数据源
		Datasource datasource = workspace.getDatasources().open(datasourceConnectionInfo);
		if (datasource == null) {
			Info.out("数据源打开失败!");
			return null;
		} else {
			Info.out("数据源打开成功!");
		}

		dataset = datasource.getDatasets().get("Tabular_901");
		if (dataset != null && dataset instanceof DatasetVector) {
			datasetVector = (DatasetVector) dataset;
			return datasetVector;
		}
		return datasetVector;
	}

	public void closeWorkSpace() {
		datasourceConnectionInfo.dispose();
		workspace.dispose();
		Info.out("释放资源!");
	}

	public void startRecords() throws Exception {
		cpu = getCPUByPID();
		memory = getMemByPID();
		time = getSystemDate();
		Recordset recordset = datasetVector.getRecordset(false, CursorType.DYNAMIC);
		LinkedHashMap<String, Object> records = new LinkedHashMap<>();
		records.put("方法名", message.getMethodName());
		records.put("startTime", time);
		records.put("startCPU", cpu);
		records.put("startMemery", memory);
		recordset.addNew(null, records);
		recordset.update();
	}

	public void endRecords() throws Exception {
		cpu = getCPUByPID();
		memory = getMemByPID();
		time = getSystemDate();
		Recordset recordset = datasetVector.getRecordset(false, CursorType.DYNAMIC);
		recordset.moveTo(recordset.getRecordCount() - 1);
		recordset.edit();
		recordset.setFieldValue("endTime", time);
		recordset.setFieldValue("endCPU", cpu);
		recordset.setFieldValue("endMemery", memory);
		recordset.update();
	}

	public String getSystemDate() {
		Date date = new Date();
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(date);
		return time;
	}

}
